<template>
  <div>
    <el-form  :inline="true" :model="queryParams" class="demo-form-inline">
      <el-form-item label="人员姓名">
        <el-input v-model="queryParams.persName" placeholder="人员姓名"></el-input>
      </el-form-item>
      <el-form-item label="所属公司">
        <el-select v-model="queryParams.coId" placeholder="所属公司">
          <el-option v-for=" item in  companyList "  :key="item.coId"    :label="item.coName" :value="item.coId"        ></el-option>

        </el-select>
      </el-form-item>
      <el-form-item label="所属公司s">
        <el-checkbox-group v-model="coIdList">
          <el-checkbox  v-for=" item in  companyList "  :key="item.coId"    :label="item.coId"    >{{item.coName}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="query">查询</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" @click="addHandler" size="mini">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete"  @click="deleteHandler()" size="mini">删除</el-button>
      </el-col>
    </el-row>
    <br>
    <el-table :data="tableData"
              v-loading="loading"
              stripe border
              @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column type="index" label="序号" ></el-table-column>
      <el-table-column prop="persId" label="人员主键" width="140"></el-table-column>
      <el-table-column prop="coName" label="公司" width="240"></el-table-column>
      <el-table-column prop="persName"  label="人员姓名" width="140"></el-table-column>
      <el-table-column prop="persSex" label="人员性别" width="140">
        <template #default="scope">
          <el-tag  v-if = "scope.row.persSex == 0"  type="danger">女</el-tag>
          <el-tag  v-if = "scope.row.persSex == 1"  type="primary">男</el-tag>

        </template>
      </el-table-column>
      <el-table-column prop="persInDate"  :formatter="formatDate"  label="入职时间" width="140"></el-table-column>
      <el-table-column prop="persSalary" label="薪水" width="140"></el-table-column>
      <el-table-column prop="persRemark"  :formatter="formatStr"  label="备注" ></el-table-column>
      <el-table-column  label="操作" >
        <template slot-scope="scope" >
          <el-button type="warning" size="mini" @click="editHandler(scope.row.persId)">修改</el-button>
          <el-button type="danger" size="mini" @click="deleteHandler(scope.row.persId)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>

    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pageNum"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[5, 10, 50, 100]"
        :page-size="10"
        >
    </el-pagination>


    <el-dialog
        :title="title"
        :visible.sync="dialogVisible"
        width="50%"  append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules"  label-width="80px">
        <el-form-item label="公司" prop="coId"  >
          <el-select v-model="form.coId" placeholder="所属公司">
            <el-option v-for=" item in  companyList "  :key="item.coId"    :label="item.coName" :value="item.coId"        ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="人员姓名" prop="persName"  >
          <el-input v-model="form.persName"></el-input>
        </el-form-item>
        <el-form-item label="人员性别" prop="persSex"  >

          <el-radio-group v-model="form.persSex">
            <el-radio :label="0">女</el-radio>
            <el-radio :label="1">男</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="入职时间" prop="persInDate"  >
          <el-date-picker type="date" placeholder="选择入职时间" v-model="form.persInDate" ></el-date-picker>
        </el-form-item>
        <el-form-item label="薪水" prop="persSalary"  >
          <el-input-number v-model="form.persSalary"></el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="persRemark"  >
          <el-input type="textarea" :rows="5"  v-model="form.persRemark"></el-input>

        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="onSubmit">保 存</el-button>
        </span>
    </el-dialog>

  </div>
</template>

<script>

import { editPage, editSave, addSave, listPerson, deletePersons } from "@/api/demo/Person.js"
import { listCompany } from "@/api/demo/Company.js"


export default {

  name: "Test",
  data() {
    return {
      tableData: [],
      total:0,
      queryParams:{
        pageNum:1,
        pageSize:10,
        persName:null,
        coId:null,
        coIds:null
      },
      coIdList:[],
      loading: false,
      companyList :[],



      // 添加 / 修改
      // 对话窗显隐
      dialogVisible:false,
      // 对话窗标题
      title:"",

      // 添加/修改 数据封装对象
      form : {
        persId: null,
        coId: null,
        persName: null,
        persSex: 1,
        persInDate: null,
        persSalary: null,
        persRemark: null
      },

      // 添加/修改 校验规则
      rules: {
        persName: [
          { required: true, message: '请输入人员名称', trigger: 'blur' },
          { min: 3, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],

      },
      // 删除
      // 用于删除的id集合
      ids:[],

    }
  },
  created() {
    this.getList()
    this.getCompanyList()
  },
  methods: {
    getCompanyList(){
      listCompany().then(resp=>{
        this.companyList = resp.data

      })
    },

    /**
     * 打开 添加 对话窗
     */
    addHandler(){
      this.resetForm()
      this.title="添加信息"
      this.dialogVisible = true
    },

    /**
     * 清空form的信息
     */
    resetForm(){
      this.form={
        persId: null,
        coId: null,
        persName: null,
        persSex: 1,
        persInDate: null,
        persSalary: null,
        persRemark: null
      }
    },

    /**
     *打开 修改 对话窗
     */
    editHandler(id){
      console.log(id)

      editPage(id).then(resp=>{
        console.log( resp )
        this.form = resp.data
        this.title="修改信息"
        this.dialogVisible = true
      })
    },
    /**
     * 添加修改的表单提交
     * @returns {string}
     */
    onSubmit() {
      // 启动校验
      this.$refs["form"].validate(  (valid) => {
        if (valid) {
          // 通过 了校验

          if(this.form.persId){
            // 修改
            editSave(this.form)
                .then(resp=>{
                  // 明确的提示
                  if (resp.code == 200) {
                    this.$message({
                      message: '保存成功',
                      type: 'success'
                    });

                    // 刷新表格
                    this.getList();
                    this.dialogVisible = false

                  }else{
                    this.$message({
                      message: '保存失败',
                      type: 'warning'
                    });
                  }
                })
          }else{
            // 添加
                addSave(this.form)
                .then(resp=>{
                  // 明确的提示
                  if (resp.code == 200) {
                    this.$message({
                      message: '保存成功',
                      type: 'success'
                    });

                    // 刷新表格
                    this.getList();
                    this.dialogVisible = false

                  }else{
                    this.$message({
                      message: '保存失败',
                      type: 'warning'
                    });
                  }
                })
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });

    },





    query(){
      this.getList()
    },
    handleSizeChange(val){
      console.log(val)
      this.queryParams.pageSize = val
      this.getList()
    },
    handleCurrentChange(val){
      console.log(val)
      this.queryParams.pageNum = val
      this.getList()
    },

    formatIfElse(r,c,v,i){
      return v==1?'男':'女'
    },

    formatStr(r,c,v,i){
      return v.length>10?v.substring(0,10)+"...":v
    },
    formatDate(row, column, cellValue, index){
      // console.log(row, column, cellValue, index)
      let date = new Date(cellValue);

      let o = {
        'y': date.getFullYear(),
        'm': (date.getMonth() + 1).toString().padStart(2, '0'),
        'd': date.getDate().toString().padStart(2, '0'),
        'h': date.getHours().toString().padStart(2, '0'),
        'i': date.getMinutes().toString().padStart(2, '0'),
        's': date.getSeconds().toString().padStart(2, '0')
      };

      return o.y + "-" + o.m + "-" + o.d;
    },
    getList(){

      console.log("checkbox:", this.coIdList )
      this.queryParams.coIds = this.coIdList.join(",")

      this.loading = true
      listPerson(this.queryParams).then(resp=>{
        this.tableData = resp.rows
        this.loading = false
        this.total = resp.total
      })
    },

    /**
     * 多选 选中
     */
    handleSelectionChange(val){
      // console.log(val)
      this.ids = val.map(item=>item.persId)
      console.log(this.ids)
    },

    /**
     * 删除处理
     */
    deleteHandler(id){
      console.log(id)

      let idss = id || this.ids.join(",")

      if(!idss){
        this.$message({
          message: '请选择要删除的记录',
          type: 'warning'
        });
        return
      }


      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletePersons(idss)
         .then(resp=>{
          console.log(resp)
          // 明确的提示
          if (resp.code == 200) {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            // 刷新表格
            this.getList();

          }else{
            this.$message({
              message: '删除失败',
              type: 'warning'
            });
          }

        })
            .catch(err=>{
          console.log( err )
          this.$message.error('删除异常');
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });


    },

  }
}
</script>

<style scoped lang="scss">

</style>
